//
//  ScoreClient.m
//  iMine
//
//  Created by gaoxiang on 09-3-26.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "ScoreClient.h"
#import "GameLevelTopInfo.h"
#import "PlayerScoreInfo.h"

#define SCOREINFOS_DOC	@"ScoreInfos_DocString"

static ScoreClient *_instance;

@implementation ScoreClient

@synthesize levelDataDic;

+ (id)instance
{
	if (!_instance)
		_instance = [[ScoreClient alloc] init];
	
	return _instance;
}

+ (NSString *)requestUrlStringForGetTopScroes
{
	NSString *action = @"get";
	return [NSString stringWithFormat:APP_URL, action, @""];
}

+ (NSString *)requestUrlStringForSendUserScore:(NSString *)playername gameLevel:(int)level elapsedTime:(int)second
{
	NSString *action = @"new";
	NSString *params = [NSString stringWithFormat:
						@"&player=%@&"
						"level=%d&"
						"elapsed=%d", [playername stringByAddingPercentEscapesUsingEncoding:
										  NSUTF8StringEncoding], level, second];
	return [NSString stringWithFormat:APP_URL, action, params];
}

+ (void)sendPlayerScoreToServer:(NSString *)playername playedLevel:(int)level elapsedTime:(int)second
{
	NSString *urlString = [ScoreClient requestUrlStringForSendUserScore:playername gameLevel:level elapsedTime:second];
	//NSLog(@"urlStrign is : %@", urlString);
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]
											 cachePolicy:NSURLRequestReloadIgnoringCacheData
										 timeoutInterval:30];
	NSData *urlData;
	NSURLResponse *response;
	NSError *error;
	urlData = [NSURLConnection sendSynchronousRequest:request
									returningResponse:&response
												error:&error];
	if (!urlData) {
		NSAlert *alert = [NSAlert alertWithError:error];
		[alert runModal];
		return;
	}
	
//#ifdef DEBUG
	NSLog(@"%@", [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]);
//#endif
}

+ (NSDictionary *)getTop10FromServer
{
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[ScoreClient requestUrlStringForGetTopScroes]]
											 cachePolicy:NSURLRequestReloadIgnoringCacheData
										 timeoutInterval:30];
	
	NSData *urlData;
	NSURLResponse *response;
	NSError *error;
	urlData = [NSURLConnection sendSynchronousRequest:request
									returningResponse:&response
												error:&error];
	if (!urlData) {
		NSAlert *alert = [NSAlert alertWithError:error];
		[alert runModal];
		return nil;
	}
	NSXMLDocument *doc = [[NSXMLDocument alloc] initWithData:urlData
													options:0
													  error:&error];
	if (!doc) {
		NSAlert *alert = [NSAlert alertWithError:error];
		[alert runModal];
		return nil;
	}
	
/*
 <?xml version="1.0" encoding="utf-8"?>
 <response>
	<scores>
		<level name="Beginner" value="1">
			<scoreInfo>
				<playername>gaoxiang</playername>
				<playerscore>100</playerscore>
			</scoreInfo>
		</level>
		<level name="Novice" value="2">
		</level>
		<level name="Expert" value="3">
		</level>
	</scores>
 </response>
 
 */
	NSDictionary *levels = [ScoreClient parseDataFromXML:doc];
	
	[[NSUserDefaults standardUserDefaults] setObject:[doc XMLString] forKey:SCOREINFOS_DOC];
	[[NSUserDefaults standardUserDefaults] synchronize];
	
	[[[ScoreClient instance] levelDataDic] release];
	[[ScoreClient instance] setLevelDataDic:levels];
	return levels;
}

+ (NSDictionary *)parseDataFromXML:(NSXMLDocument *)doc
{
	NSError *error;
	NSArray *levelNodes = [doc nodesForXPath:@"response/scores/level" error:&error];
	NSMutableDictionary *levels = [[NSMutableDictionary alloc] init];
	NSXMLNode *levelNode = nil;
	for (levelNode in levelNodes) {
		NSXMLNode *nameAttr = [[levelNode nodesForXPath:@"@name" error:&error] objectAtIndex:0];
		NSString *levelname = [[nameAttr stringValue] retain];
		//NSLog(@"%@ = %@", [nameAttr name], levelname);
		
		NSXMLNode *valueAttr = [[levelNode nodesForXPath:@"@value" error:&error] objectAtIndex:0];
		int levelvalue = [[valueAttr stringValue] intValue];
		//NSLog(@"%@ = %d", [valueAttr name], levelvalue);
		
		NSMutableArray *scoreInfos = [[NSMutableArray alloc] init];
		NSArray *infoNodes = [levelNode nodesForXPath:@"scoreInfo" error:&error];
		NSXMLNode *infoNode = nil;
		for (infoNode in infoNodes)
		{
			NSXMLNode *playernameNode = [[infoNode nodesForXPath:@"playername" error:&error] objectAtIndex:0];
			NSXMLNode *playerscoreNode = [[infoNode nodesForXPath:@"playerscore" error:&error] objectAtIndex:0];
			PlayerScoreInfo *psi = [[PlayerScoreInfo alloc] initWithPlayerName:[[playernameNode stringValue] retain] andLevel:levelvalue andElapsedTime:[[playerscoreNode stringValue] intValue]];
			[scoreInfos addObject:psi];
		}
		GameLevelTopInfo *glti = [[GameLevelTopInfo alloc] initWithLevelName:levelname andLevelValue:levelvalue andScoreInfos:scoreInfos];
		[levels setObject:glti forKey:[glti levelName]];
	}
	
	[levels retain];
	return levels;
}

+ (NSDictionary *)gameLevelData
{
	NSError *error;
	if (![[ScoreClient instance] levelDataDic])
	{
		NSString *xmlString = [[NSUserDefaults standardUserDefaults] stringForKey:SCOREINFOS_DOC];
		NSXMLDocument *doc = nil;
		if (xmlString)
		{
			doc = [[NSXMLDocument alloc] initWithXMLString:xmlString options:0 error:&error];
		}
		if (!doc)
		{
			NSMutableDictionary *tmpdic = [[NSMutableDictionary alloc] init];
			[tmpdic setObject:[[GameLevelTopInfo alloc] initWithLevelName:@"Beginner" andLevelValue:1 andScoreInfos:[[NSArray alloc] init]] forKey:@"Beginner"];
			[tmpdic setObject:[[GameLevelTopInfo alloc] initWithLevelName:@"Novice" andLevelValue:1 andScoreInfos:[[NSArray alloc] init]] forKey:@"Novice"];
			[tmpdic setObject:[[GameLevelTopInfo alloc] initWithLevelName:@"Expert" andLevelValue:1 andScoreInfos:[[NSArray alloc] init]] forKey:@"Expert"];
			[tmpdic retain];
			[[ScoreClient instance] setLevelDataDic:tmpdic];
		}
		else
		{
			[[ScoreClient instance] setLevelDataDic:[ScoreClient parseDataFromXML:doc]];
		}
	}
	return [[ScoreClient instance] levelDataDic];
}

- (id)init
{
	if (![super init])
		return nil;
	
	levelDataDic = nil;
	
	return self;
}

- (void)dealloc
{
	[levelDataDic release];
	[super dealloc];
}

@end
